package org.mx.dal.config;

import org.mx.dal.service.GeneralAccessor;
import org.mx.dal.service.GeneralDictAccessor;
import org.mx.dal.service.impl.GeneralAccessorMongoImpl;
import org.mx.dal.service.impl.GeneralDictAccessorMongoImpl;
import org.mx.spring.config.SpringConfig;
import org.mx.spring.session.SessionDataStore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDbFactory;

import com.mongodb.ConnectionString;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;

/**
 * 基于Mongodb的DAL实现的Java Configure定义 扫描：org.mx.dal.service.impl中的组件
 * 加载配置：classpath:mongodb.properties
 *
 * @author : john.peng date : 2017/10/8
 */
@Import({ DalConfig.class, SpringConfig.class })
@ComponentScan({ "org.mx.dal.service.impl" })
public class DalMongodbConfig {

	/**
	 * 默认的构造函数
	 */
	public DalMongodbConfig() {
		super();
	}

	/**
	 * 创建连接字符串
	 * 
	 * @param env Spring环境
	 * @return 连接字符串
	 */
	@Bean
	public ConnectionString connectionString(Environment env) {
		return new ConnectionString(env.getProperty("mongo.connection"));
	}

	/**
	 * 创建MongoClient
	 * 
	 * @param connectionString 连接字符串
	 * @return MongoClient
	 */
	@Bean
	public MongoClient mongoClient(ConnectionString connectionString) {
		return MongoClients.create(connectionString);
	}

	/**
	 * 根据配置创建MongoDB数据库工厂
	 *
	 * @param mongoClient      MongoDb Client
	 * @param connectionString MongoDB连接字符串对象
	 * @return MongoDB数据库工厂
	 */
	@Bean
	public MongoDbFactory mongoDbFactory(MongoClient mongoClient, ConnectionString connectionString) {
		return new SimpleMongoClientDbFactory(mongoClient, connectionString.getDatabase());
	}

	/**
	 * 创建MongoDB模版工具
	 *
	 * @param mongoDbFactory MongoDB数据库工厂
	 * @return 模版工具
	 */
	@Bean(name = "mongoTemplate")
	public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory) {
		return new MongoTemplate(mongoDbFactory);
	}

	/**
	 * 创建基于MongoDB的数据对象Accessor
	 * 
	 * @param template         MongoTemplate
	 * @param sessionDataStore 会话数据存储
	 * @return Accessor
	 */
	@Bean(name = "generalAccessorMongodb")
	public GeneralAccessor generalAccessorMongodb(MongoTemplate template, SessionDataStore sessionDataStore) {
		return new GeneralAccessorMongoImpl(template, sessionDataStore);
	}

	/**
	 * 创建基于MongoDB的字典对象Accessor
	 * 
	 * @param template         MongoTemplate
	 * @param sessionDataStore 会话数据存储
	 * @return Accessor
	 */
	@Bean(name = "generalDictAccessorMongodb")
	public GeneralDictAccessor generalDictAccessorMongodb(MongoTemplate template, SessionDataStore sessionDataStore) {
		return new GeneralDictAccessorMongoImpl(template, sessionDataStore);
	}
}
